from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page, get_first_error

import os

import json

from Spiders.dailianwanzi.BSMain import DaiLianWanZi

from BloodSpiderAPI.apis.dailianwanzi import utils

from BloodSpiderAPI.auto_utils import money_conversion # 金额转换工具

from BloodSpiderAPI import models

from BloodSpiderAPI.apis.order_v2 import utils as order_v2_utils

from BloodSpiderModel.spider_tools.common_utils import GeneralToolkit



gen_toolkit = GeneralToolkit()
dlwz = DaiLianWanZi()

with open("db_small_json/dailianwanzi/English_Sensitive_Words_for_Order_Post_Titles_on_Dai_lian_Wanzi.json", "r", encoding="utf-8") as f:
    # 敏感词列表
    sensitive_words = json.load(f)


# 发布订单
def publish_order(request):
    order_amount = money_conversion.calculate_commission_and_remaining(request.GET.get("amount"))
    # 获取请求参数
    title = request.GET.get("title")
    amount = order_amount[0]
    hour = request.GET.get("hour")
    dailiantong_order_id = request.GET.get("dailiantong_order_id")
    gameRegionName = request.GET.get("gameRegionName")
    baozhengjin = money_conversion.calculate_average_list(order_amount[1], margin_rate=2)
    
    uncompleted_profit = money_conversion.safe_subtract(money_conversion.safe_add(baozhengjin[0], baozhengjin[1]) , money_conversion.safe_add(request.GET.get("securityDeposit"), request.GET.get("efficiencyDeposit")) ) 
    if uncompleted_profit is None:
        return response_dict(
            code=1,
            message="订单完成后的利润计算失败",
        )

    # 检测订单标题是否包含敏感词
    if gen_toolkit.check_common_substrings(title, sensitive_words):
        return response_dict(
            code=1,
            message="订单标题包含敏感词",
        )
    

    # 发布订单
    order_detail = dlwz.publish_order(
        title=title,
        amount=order_amount[1],
        hour=hour,
        securityDeposit=baozhengjin[0],
        efficiencyDeposit=baozhengjin[1],
        gameRegionName=gameRegionName,
    )

    


    # 过滤订单详情
    order_detail = utils.filter_publish_order(order_detail)
    if order_detail["code"] != 0:
        return response_dict(
            code=order_detail.get("code"),
            message=order_detail.get("message"),
        )

    # 对订单完成收益进行减1元操作
    original_profit = amount
    service_fee = 1.0
    final_profit = money_conversion.safe_subtract(original_profit, service_fee)
    if final_profit is None:
        return response_dict(
            code=1,
            message="订单完成收益计算失败",
        )
    
    # 准备备注信息
    remark = f"原收益金额：{original_profit}元，已扣除代练通服务费：{service_fee}元，最终净利润：{final_profit}元"

    publish_order_response = models.OrderListV2.objects.create(
        dailiantong_order_id=dailiantong_order_id,
        order_name=title,
        receiving_price = request.GET.get("amount"),
        receiving_margin = request.GET.get("securityDeposit"),
        receiving_efficiency_fee = request.GET.get("efficiencyDeposit"),
        receiving_delivery_time = request.GET.get("hour"),
        receiving_server = order_detail["data"]["gameRegionName"],
        posting_price = order_amount[1],
        posting_security_fee = baozhengjin[0],
        posting_efficiency_fee = baozhengjin[1],
        uncompleted_profit = uncompleted_profit,
        dailianwangzi_order_id = order_detail["data"]["tradeNo"],
        completed_profit = final_profit,
        status = 1,
        remark = remark
    )



    
    
    # 返回响应
    return response_dict(
        code=order_detail.get("code"),
        message=order_detail.get("message"),
        data={
            "tradeNo": order_detail.get("tradeNo"),
            "status": order_detail.get("status"),
            "dailianwangzi_data": order_v2_utils.utils_model_to_dict(publish_order_response)
        }
    )


# 获取我的余额
def get_my_balance(request):
    # 获取我的余额
    balance_detail = dlwz.get_my_balance()

    code = 0
    message = "获取余额成功"
    if balance_detail.get("code") == 10000:
        code = 0
    else:
        code = 1
        message = balance_detail.get("message")

    # 返回响应
    return response_dict(
        code=code,
        message=message,
        data=balance_detail.get("data")
    )
    

# 取消订单
def cancel_order(request):
    # 获取请求参数
    order_id = request.GET.get("order_id")

    # 取消订单
    order_detail = dlwz.cancel_order(
        orderId=order_id,
    )

    code = 0
    message = "取消订单成功"
    if order_detail.get("code") == 10000:
        code = 0
    else:
        code = 1
        message = order_detail.get("message")
        return response_dict(
            code=code,
            message=message,
        )

    models.OrderListV2.objects.filter(dailianwangzi_order_id=order_id).update(status=11)

    # 返回响应
    return response_dict(
        code=code,
        message=message,
    )


# 查询订单
def query_order(request):
    # 获取请求参数
    order_id = request.GET.get("order_id")
    page = int(request.GET.get("page", 1))
    page_size = int(request.GET.get("page_size", 10))

    # 查询订单
    order_detail = dlwz.query_order(
        orderId=order_id,
        page=page,
        pageSize=page_size,
    )

    code = 0
    if order_detail.get("code") == 10000:
        code = 0
    else:
        code = 1
        return response_dict(
            code=code,
            message="查询失败 空数据",
        )

    order_list = []
    for order in order_detail.get("data").get("ordersList"):
        order_list.append({
            "order_id": order.get("tradeNo"),
            "status": order.get("status"),
            "title": order.get("title"),
            "gameName": order.get("gameName"),
            "gameRegionName": order.get("gameRegionName"),
            "gameServerName": order.get("gameServerName"),
            "amount": order.get("amount"),
            "hour": order.get("hour"),
            "securityDeposit": order.get("securityDeposit"),
            "efficiencyDeposit": order.get("efficiencyDeposit"),
        })

    # 返回响应
    return response_dict(
        code= code,
        message="查询成功",
        data=order_list
    )



# 获取我的全部订单
def get_my_orders(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    try:
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        if request.GET.get("page_size") is None:
            page_size = request.GET.get("limit", 10)

        # 获取我的全部订单
        order_detail = dlwz.get_my_orders(page, page_size)
        order_list = []
        for order in order_detail.get("data").get("ordersList"):
            order_list.append({
                "order_id": order.get("tradeNo"),
                "status": order.get("status"),
                "title": order.get("title"),
                "gameName": order.get("gameName"),
                "gameRegionName": order.get("gameRegionName"),
                "gameServerName": order.get("gameServerName"),
                "amount": order.get("amount"),
                "hour": order.get("hour"),
                "securityDeposit": order.get("securityDeposit"),
                "efficiencyDeposit": order.get("efficiencyDeposit"),
            })
        
        return response_dict(data={
            "page": order_detail["data"]["page"],
            "order_list": order_list,
        }, message="获取成功")
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)



# 获取我的订单列表-v2版本：支持按照状态获取
def get_my_orders_v2(request):
    if request.method != 'GET':
        return response_dict(message="请使用GET请求", code=1)

    try:
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        if request.GET.get("page_size") is None:
            page_size = request.GET.get("limit", 10)
        table_type = int(request.GET.get("table_type", 0))

        # 获取我的全部订单
        order_detail = dlwz.get_order_list_v2(table_type, page, page_size)
        order_list = []
        for order in order_detail.get("data").get("ordersList"):
            order_list.append({
                "order_id": order.get("tradeNo"),
                "status": order.get("status"),
                "title": order.get("title"),
                "gameName": order.get("gameName"),
                "gameRegionName": order.get("gameRegionName"),
                "gameServerName": order.get("gameServerName"),
                "amount": order.get("amount"),
                "hour": order.get("hour"),
                "securityDeposit": order.get("securityDeposit"),
                "efficiencyDeposit": order.get("efficiencyDeposit"),
            })
        
        return response_dict(data={
            "page": order_detail["data"]["page"],
            "order_list": order_list,
        }, message="获取成功")
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)
